package com.tdt.alarm.controller.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.tdt.alarm.R;
import com.tdt.alarm.model.Song;
import com.tdt.alarm.model.SongAdapter;
import com.tdt.alarm.model.seekbar.SeekArc;
import com.tdt.alarm.model.seekbar.SeekArc.OnSeekArcChangeListener;
import com.tdt.alarm.service.MusicService;
import com.tdt.alarm.service.MusicService.MusicBinder;

public class Fragment2 extends Fragment {
	private List<String> listMusics;
	EditText editTextLullTime;
	ListView listViewMusics;
	SeekArc mSeekArcMin;
	Button btnOK;
	Button btnCancel;
	MediaPlayer mp;
	CountDownTimer cdt;
	ImageView imageView;

	private static ArrayList<Song> songList;
	private ListView songView;
	private MusicService musicSrv;
	private Intent playIntent;
	private boolean musicBound = false;
	private boolean playingStatus;
	private RingtoneManager mRingtoneManager;
	private final int maxTime = 60;
	private final int mutils = 1;
	private int oneMin = 1000 * 60;

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.activity_lull, container, false);
		mSeekArcMin = (SeekArc) view.findViewById(R.id.seekArcLullTime);
		editTextLullTime = (EditText) view.findViewById(R.id.editTextLullTime);
		btnOK = (Button) view.findViewById(R.id.btnLullOK);
		btnCancel = (Button) view.findViewById(R.id.btnLullCancell);
		songView = (ListView) view.findViewById(R.id.listViewSong);
		imageView = (ImageView) view.findViewById(R.id.imageViewButton);
		songList = new ArrayList<Song>();

		getSongList();
		Collections.sort(songList, new Comparator<Song>() {
			public int compare(Song a, Song b) {
				return a.getTitle().compareTo(b.getTitle());
			}
		});

		SongAdapter songAdt = new SongAdapter(getActivity(), songList);
		songView.setAdapter(songAdt);
		songView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// musicSrv.setSong(position);
				// musicSrv.playSong();
			}
		});

		mSeekArcMin.setmMax(maxTime);
		mSeekArcMin.setArcRotation(0);
		mSeekArcMin.setStartAngle(0);
		mSeekArcMin.setSweepAngle(360);
		mSeekArcMin.setArcWidth(20);
		mSeekArcMin.setProgressWidth(5);
		mSeekArcMin.setRoundedEdges(true);
		mSeekArcMin.setTouchInSide(true);
		mSeekArcMin.setClockwise(true);
		

		mSeekArcMin.setOnSeekArcChangeListener(new OnSeekArcChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekArc seekArc) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekArc seekArc) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekArc seekArc, int progress,
					boolean fromUser) {
				int min = progress * mutils;
//				if(progress == maxTime ){
//					editTextLullTime.setFocusable(true);
//				} else {
//					editTextLullTime.setFocusable(false);
//				}
				editTextLullTime.setText(min + "");
			}
		});
		

		btnOK.setOnClickListener(buttonClickHandler);
		btnCancel.setOnClickListener(buttonClickHandler);
		if (musicSrv == null) {
			playingStatus = false;
			imageView.setImageResource(R.drawable.sleeping_cat);
		}

		imageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!playingStatus) { // music is playing
					if (cdt != null) {
						cdt.cancel();
					}
					int countDownDur = Integer.parseInt(editTextLullTime.getText().toString());
					if (countDownDur <= 0) {
						Toast.makeText(getActivity(),
								"Please choose count down time !",
								Toast.LENGTH_SHORT).show();
					} else {
						ArrayList<Song> chooseSong = getChoosedSong();
						if (chooseSong.size() > 0) {
							
							mSeekArcMin.setmMax(countDownDur);
							mSeekArcMin.setmProgress(countDownDur);
							
							countDownDur *= oneMin;
							cdt = new CountDownTimer(countDownDur, 5 * 1000) {

								@Override
								public void onTick(long millisUntilFinished) {
									int minUtilFinished = (int) (millisUntilFinished / oneMin);
									editTextLullTime.setText(String
											.valueOf(minUtilFinished + 1));
									mSeekArcMin.setProgress(minUtilFinished + 1);
								}

								@Override
								public void onFinish() {
									Toast.makeText(getActivity(),
											"Have a nice dream ! My love...",
											Toast.LENGTH_SHORT).show();
									musicSrv.stop();
									mSeekArcMin.setmMax(maxTime);
									mSeekArcMin.setProgress(0);
									editTextLullTime.setText("0");
									imageView.setImageResource(R.drawable.sleeping_cat);
								}
							};
							
							musicSrv.setList(chooseSong);
							musicSrv.setSong(0);
							musicSrv.playSong();
							cdt.start();
							imageView.setImageResource(R.drawable.running_cat);
							playingStatus = true;
						} else {
							Toast.makeText(getActivity(),
									"Please choose at least 01 song !",
									Toast.LENGTH_SHORT).show();
						}
					}
				} else { // music stoped
					if (musicSrv != null) {
						musicSrv.stop();
					}
					if (cdt != null) {
						cdt.cancel();
					}
					playingStatus = false;
					imageView.setImageResource(R.drawable.sleeping_cat);
					mSeekArcMin.setmMax(maxTime);
					mSeekArcMin.setProgress(0);
				}
			}
		});

		return view;
	}

	@Override
	public void onStart() {
		super.onStart();
		if (playIntent == null) {
			playIntent = new Intent(getActivity(), MusicService.class);
			getActivity().bindService(playIntent, musicConnection,
					Context.BIND_AUTO_CREATE);
			getActivity().startService(playIntent);
		}
	}

	private OnClickListener buttonClickHandler = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// Button OK handle
			if (v.getId() == btnOK.getId()) {
				if (cdt != null) {
					cdt.cancel();
				}

				// Get count down time from textview
				// int countDownDur =
				// Integer.parseInt(textViewLullTime.getText()
				// .toString());

				int countDownDur = mSeekArcMin.getmProgress();
				if (countDownDur <= 0) {
					Toast.makeText(getActivity(),
							"Please choose count down time !",
							Toast.LENGTH_SHORT).show();
				} else {
					countDownDur *= 1000;
					cdt = new CountDownTimer(countDownDur, 1000) {

						@Override
						public void onTick(long millisUntilFinished) {
							int secondsUtilFinished = (int) (millisUntilFinished / 1000);
							editTextLullTime.setText(String
									.valueOf(secondsUtilFinished));
							mSeekArcMin.setProgress(secondsUtilFinished);
						}

						@Override
						public void onFinish() {
							Toast.makeText(getActivity(),
									"Have a nice dream ! My love...",
									Toast.LENGTH_SHORT).show();
							musicSrv.stop();
							mSeekArcMin.setProgress(0);
							editTextLullTime.setText("0");
						}
					};

					ArrayList<Song> chooseSong = getChoosedSong();
					if (chooseSong.size() > 0) {
						musicSrv.setList(chooseSong);
						musicSrv.setSong(0);
						musicSrv.playSong();
						cdt.start();
					} else {
						Toast.makeText(getActivity(),
								"Please choose at least 01 song !",
								Toast.LENGTH_SHORT).show();
					}
				}
			} else {
				// Intent t = new Intent(getActivity(), Ringtones.class);
				// startActivity(t);
				if (musicSrv != null) {
					musicSrv.stop();
				}
				if (cdt != null) {
					cdt.cancel();
				}
			}
		}
	};

	/**
	 * Get song list from the phone
	 */
	public void getSongList() {
		ContentResolver musicResolver = getActivity().getContentResolver();
		Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
		Cursor musicCursor = musicResolver.query(musicUri, null, null, null,
				null);

		if (musicCursor != null && musicCursor.moveToFirst()) {
			// get columns
			int titleColumn = musicCursor
					.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
			int idColumn = musicCursor
					.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
			int artistColumn = musicCursor
					.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
			// add songs to list
			do {
				long thisId = musicCursor.getLong(idColumn);
				String thisTitle = musicCursor.getString(titleColumn);
				String thisArtist = musicCursor.getString(artistColumn);
				songList.add(new Song(thisId, thisTitle, thisArtist, false));
			} while (musicCursor.moveToNext());
		}
	}

	/**
	 * Connect to the service
	 */
	private ServiceConnection musicConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			MusicBinder binder = (MusicBinder) service;
			// get service
			musicSrv = binder.getService();
			// pass list
			ArrayList<Song> chooseSongs = getChoosedSong();
			musicSrv.setList(chooseSongs);
			musicBound = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			musicBound = false;
		}
	};

	/**
	 * Play the song if picked
	 * 
	 * @param view
	 */
	public void songPicked(View view) {
		musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
		musicSrv.playSong();
	}

	@Override
	public void onDestroy() {
		getActivity().stopService(playIntent);
		musicSrv = null;
		super.onDestroy();
	}

	/**
	 * Get the list of song which are choosed
	 * 
	 * @return
	 */
	private ArrayList<Song> getChoosedSong() {
		ArrayList<Song> result = new ArrayList<Song>();
		for (Song s : songList) {
			if (s.isChoose()) {
				result.add(s);
			}
		}
		return result;
	}

	/**
	 * Set the song in this position with choose value
	 * 
	 * @param position
	 * @param isChoose
	 */
	public static void setChoose(int position, boolean isChoose) {
		songList.get(position).setChoose(isChoose);
	}

}
